package com.spring.cloud.eurekaclientzuul.route;

import com.spring.cloud.eurekaclientzuul.dao.RouteDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.netflix.zuul.filters.ZuulProperties;
import org.springframework.cloud.netflix.zuul.filters.discovery.DiscoveryClientRouteLocator;
import org.springframework.cloud.netflix.zuul.filters.discovery.ServiceRouteMapper;

import java.util.LinkedHashMap;
import java.util.Map;

//动态路由需要继承DiscoveryClientRouteLocator
//实现 locateRoutes 方法
public class MyRouteLocator extends DiscoveryClientRouteLocator {

    //数据库获取路由表规则 对象
    @Autowired
    private RouteDao routeDao;

    //构造方法
    public MyRouteLocator(String servletPath,
                          DiscoveryClient discovery,
                          ZuulProperties properties,
                          ServiceRouteMapper serviceRouteMapper,
                          ServiceInstance localServiceInstance) {
        //父类构造方法
        super(servletPath, discovery, properties, serviceRouteMapper, localServiceInstance);
    }

    @Override       //动态路由表 的核心方法
    protected LinkedHashMap<String, ZuulProperties.ZuulRoute> locateRoutes() {

        //调用父类方法,加载静态配置的路由规则
        LinkedHashMap<String,ZuulProperties.ZuulRoute>resultMap = super.locateRoutes();
        //加载数据库配置的路由规则
        Map<String,ZuulProperties.ZuulRoute> dbMap = routeDao.findEnableRoutes();
        //将数据库中的路由规则 追加到 原来的静态路由规则内
        resultMap.putAll(dbMap);

        return resultMap;
    }
}
